<template>
  <div id="register">
    <van-form colon validate-first @failed="onFailed" @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' },{ validator: passwordValidator, message: '以字母开头，长度在6~18之间，只能包含字母、数字和下划线'}]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          登陆
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  #register{
    margin-top: 40px;
  }
</style>

<script lang="ts">
// @ is an alias to /src
import { Form,Field,Button,Radio,RadioGroup,Calendar } from 'vant';
import { Component, Prop, Vue, Watch, Model } from 'vue-property-decorator';
import axios from '../api/axios.base';
import router from '../router';
import store from '../store/index';

Vue.use(Form).use(Field).use(Button).use(Calendar).use(Radio).use(RadioGroup);
@Component
export default class LoginComponent extends Vue {
  private readonly username: string = '';
  private readonly password: string = '';

  private passwordValidator(val: string): boolean{
    return /^\w{5,17}$/.test(val);
  }

  created(){
    store.commit('global/setShowPageLoading',false);
  }

  private onSubmit(values: any) {
    axios.post('/api/auth/login',values)
    .then((res) => {
      if(res.data.access_token){
        localStorage.setItem('access_token',res.data.access_token);
        const cb_path: any=router.currentRoute.query.cb_path;
        router.push({
          path: cb_path||'/home'
        });
      }      
    });
  }

  private onFailed(errorInfo: any) {
    console.log('failed', errorInfo);    
  }

}
</script>
